import {
  getCodeSnippetsModel,
  getCodeSnippetByIdModel,
  createCodeSnippetModel,
  updateCodeSnippetModel,
  deleteCodeSnippetModel,
} from "../model/code.js";

/**
 * 获取代码片段列表
 * @param {Object} ctx - Koa上下文
 */
export const getCodeSnippets = async (ctx) => {
  try {
    const query = ctx.query;
    const title = query.title || "";
    const pagenum = Math.abs(Number(query.pagenum)) || 1;
    const pagesize = Math.abs(Number(query.pagesize)) || 10;
    const skip = (pagenum - 1) * pagesize;

    ctx.body = await getCodeSnippetsModel(title, skip, pagesize);
  } catch (err) {
    ctx.status = 500;
    ctx.body = { error: "Failed to fetch code snippets" };
  }
};

/**
 * 获取单个代码片段
 * @param {Object} ctx - Koa上下文
 */
export const getCodeSnippetById = async (ctx) => {
  try {
    const id = ctx.params.id;
    const snippet = await getCodeSnippetByIdModel(id);

    if (!snippet) {
      ctx.status = 404;
      ctx.body = { error: "Code snippet not found" };
      return;
    }

    ctx.body = snippet;
  } catch (err) {
    ctx.status = 500;
    ctx.body = { error: "Failed to fetch code snippet" };
  }
};

/**
 * 创建新代码片段
 * @param {Object} ctx - Koa上下文
 */
export const createCodeSnippet = async (ctx) => {
  try {
    const body = ctx.request.body;
    const title = body.title;
    const code = body.code;

    if (!title || !code) {
      ctx.status = 400;
      ctx.body = { error: "Title and code are required" };
      return;
    }

    ctx.body = await createCodeSnippetModel(title, code);
    ctx.status = 201;
  } catch (err) {
    ctx.status = 500;
    ctx.body = { error: "Failed to create code snippet" };
  }
};

/**
 * 更新代码片段
 * @param {Object} ctx - Koa上下文
 */
export const updateCodeSnippet = async (ctx) => {
  try {
    const id = ctx.params.id;
    const body = ctx.request.body;
    const title = body.title;
    const code = body.code;

    if (!title && !code) {
      ctx.status = 400;
      ctx.body = { error: "At least one field (title or code) is required" };
      return;
    }

    // 检查代码片段是否存在
    const existingSnippet = await getCodeSnippetByIdModel(id);
    if (!existingSnippet) {
      ctx.status = 404;
      ctx.body = { error: "Code snippet not found" };
      return;
    }

    ctx.body = await updateCodeSnippetModel(
      id,
      title || existingSnippet.title,
      code || existingSnippet.code
    );
  } catch (err) {
    ctx.status = 500;
    ctx.body = { error: "Failed to update code snippet" };
  }
};

/**
 * 删除代码片段
 * @param {Object} ctx - Koa上下文
 */
export const deleteCodeSnippet = async (ctx) => {
  try {
    const id = ctx.params.id;

    // 检查代码片段是否存在
    const existingSnippet = await getCodeSnippetByIdModel(id);
    if (!existingSnippet) {
      ctx.status = 404;
      ctx.body = { error: "Code snippet not found" };
      return;
    }

    await deleteCodeSnippetModel(id);
    ctx.status = 204;
  } catch (err) {
    ctx.status = 500;
    ctx.body = { error: "Failed to delete code snippet" };
  }
};